package com.echo.usedsfu;

import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

import com.echo.usedsfu.entity.Information;
import com.echo.usedsfu.entity.MyImage;
import com.echo.usedsfu.persistence.PMF;
import com.google.appengine.api.datastore.Blob;

public class PlaceAdServlet extends HttpServlet {
	private static final Logger log = Logger.getLogger(PlaceAdServlet.class.getName());
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp)throws IOException{
		ServletFileUpload upload = new ServletFileUpload();
		String title = req.getParameter("title");
		String area = req.getParameter("area");
		String contact = req.getParameter("contact");
		String description = req.getParameter("description");
		String phone = req.getParameter("phone");
		String email = req.getParameter("email");
		String temp_time = req.getParameter("expire_time");
		String img_id = req.getParameter("img_id");
		Date pub_time = new Date();
		
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try{
			//get the image
//			FileItemIterator iter = upload.getItemIterator(req);
//			FileItemStream imageItem = iter.next();
//			InputStream imgStream = imageItem.openStream();
//			Blob imageBlob = new Blob(IOUtils.toByteArray(imgStream));
//			MyImage myImage = new MyImage(imageItem.getName(), imageBlob);
			
			
			DateFormat formatter = new SimpleDateFormat("MM/DD/yyyy");
		    Date expire_time = (Date)formatter.parse(temp_time);
		    Information info = new Information(title, area, contact, description, phone, email, pub_time, expire_time, img_id);
		
//		    PersistenceManager pm = PMF.get().getPersistenceManager();
			pm.makePersistent(info);
		}catch(ParseException e){
			System.err.println(e);
		}
//		catch(FileUploadException e){
//			System.err.println(e);
//		}
		finally{
			pm.close();
		}
		resp.sendRedirect("/index.jsp");
	}
}
